package ch.unisi.inf.gui.action;

import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;


/**
 * 
 * @author Mohamed.Mosa@lu.unisi.ch
 *
 * Photo chooser is responsible for opening a window for the user to 
 * choose a file.
 */

public final class PhotoChooser extends JPanel implements ActionListener {
	private final JTextArea listOfFiles;
	private final JScrollPane listScrollPane;
	private JFileChooser fc;
	private final JButton UploadButton;
	private final JButton CancelButton;

	public PhotoChooser() {
		super(new BorderLayout());

		listOfFiles = new JTextArea(10,20);
		listOfFiles.setMargin(new Insets(5,5,5,5));
		listOfFiles.setEditable(false);
		listScrollPane = new JScrollPane(listOfFiles);

		UploadButton = new JButton("Upload Photo");
		UploadButton.addActionListener(this);

		CancelButton = new JButton("Cancel");

		add(UploadButton, BorderLayout.NORTH);
		add(CancelButton, BorderLayout.SOUTH);
		add(listScrollPane, BorderLayout.CENTER);
	}

	public final void actionPerformed(ActionEvent ev) {
		// Start the file chooser.
		if (fc == null) {
			fc = new JFileChooser();

			// Enable multiple selections
			fc.setMultiSelectionEnabled(true);

			// Retrieve the selected files. This method returns empty
			// if multiple-selection mode is not enabled.
			File[] files = fc.getSelectedFiles();        

			//Here I add my custom filter
			fc.addChoosableFileFilter(new ImageFilter());

			//Here I keep the default filter "All files"     
			fc.setAcceptAllFileFilterUsed(true);

			//Add icons to my images
			fc.setFileView(new ImageFileIcon());

			//Add the preview pane.
			fc.setAccessory(new ImagePreview(fc));
		}

		//Show dialog
		int returnVal = fc.showDialog(PhotoChooser.this,"Upload");

		//Process image(s) selected
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			listOfFiles.append("Uploading Photo: " + file.getName() + ". \n");

		} 
		else {
			listOfFiles.append("Upload cancelled by user. \n");
		}

		listOfFiles.setCaretPosition(listOfFiles.getDocument().getLength());

		//Reset the file chooser for reopening
		fc.setSelectedFile(null);
	}

	/**
	 * This creates the GUI for the photo chooser and shows it.
	 */
	private static final void uploadGui() {
		//Create and set up the window.
		JFrame frame = new JFrame("Upload Window");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//Add content to the window.
		frame.add(new PhotoChooser());

		//Show the window.
		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) {

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				uploadGui();
			}
		});
	}
}